import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from "@/stores/modules/user";
import { AuthStore } from "@/stores/modules/auth";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { staticRouter, errorRouter } from '@/routers/modules/staticRouter'
import NProgress from "@/config/nprogress"
const router = createRouter({
	history: createWebHistory(),
	routes: [...staticRouter, ...errorRouter],
	strict: false,
	scrollBehavior: () => ({ left: 0, top: 0 })
})

const ROUTER_WHITE_LIST = [
	'cs'
]

router.beforeEach(async (to, from, next) => {
	const userStore = useUserStore();
	const authStore = AuthStore();

	NProgress.start();

	// 3.判断是访问登陆页，有 Token 就在当前页面，没有 Token 重置路由到登陆页
	if (to.path.toLocaleLowerCase() === '/login') {
		if (userStore.token) return next(from.fullPath);
		// resetRouter();
		return next();
	}
	// 4.判断访问页面是否在路由白名单地址(静态路由)中，如果存在直接放行
	if (ROUTER_WHITE_LIST.includes(to.path)) return next();

	// 5.判断是否有 Token，没有重定向到 login 页面
	if (!userStore.token) return next({ path: '/login', replace: true });

	// 6.如果没有菜单列表，就重新请求菜单列表并添加动态路由
	// setTimeout(async () => {
		console.log(authStore.authMenuListGet, 11111);
		// if (!authStore.authMenuListGet.length) {
			await initDynamicRouter();
		// 	return next({ ...to, replace: true });
		// }
	// })
	
	next()
})

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
	NProgress.done();
})

/**
 * @description 路由跳转错误
 * */
router.onError(error => {
	NProgress.done();
	console.warn("路由错误", error.message);
})
export default router